#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

from config import *
from generator import *

#from sqlobject import *
#sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

class View:
    def GET( self ):

        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")
      
        # 初期チェック
        #######################################################

        #ARTILCES CREATE DB
        ArticlesType.createTable(ifNotExists=True)
        Articles.createTable(ifNotExists=True)
        Posts.createTable(ifNotExists=True)
        Groups.createTable(ifNotExists=True)
        Categories.createTable(ifNotExists=True)
        #PostsCategories.createTable(ifNotExists=True)

        #ARTICLE TYPE CHECK
        for t in ARTICLES_TYPE:
            articlestype = ArticlesType.select(ArticlesType.q.id == t.get("id")).getOne(default=None)
            if articlestype is None:
                ArticlesType(   id = t.get('id'), 
                                prefix = t.get('prefix'),
                                title = t.get('title'),
                                idx = t.get('idx'),
                )
                articlestype = ArticlesType.select(ArticlesType.q.id == t.get("id")).getOne(default=None)
            else:
                prefix = t.get('prefix'),
                articlestype.title = t.get('title')
                articlestype.idx = t.get('idx')

            #設定GROUP確認
            for o in t.get('group'):
                group = Groups.select( AND( Groups.q.articlestype == articlestype , Groups.q.code == o.get('code') ) ).getOne(default=None)
                group_parent = Groups.select( AND( Groups.q.articlestype == articlestype , Groups.q.code == o.get('parent') ) ).getOne(default=None)
                if group is None:
                    Groups(
                                articlestype = articlestype,
                                code = o.get('code'),
                                parent = group_parent,
                                label = o.get('label'),
                                idx = o.get('index'),
                    )
                else:
                    group.label = o.get('label')
                    group.index = o.get('index')
                    group.parent = group_parent

            #設定CATEGORY追加
            for o in t.get('category'):
                category = Categories.select( AND( Categories.q.articlestype == articlestype , Categories.q.code == o.get('code')) ).getOne(default=None)
                category_parent = Categories.select( AND( Categories.q.articlestype == articlestype , Categories.q.code == o.get('parent')) ).getOne(default=None)
                if category is None:
                    Categories(
                                articlestype = articlestype,
                                code = o.get('code'),
                                parent = category_parent,
                                label = o.get('label'),
                                idx = o.get('index'),
                    )
                else:
                    category.label = o.get('label')
                    category.index = o.get('index')
                    category.parent = category_parent

        #ARTICLE CHECK
        for a in ARTICLES:
            articlestype = ArticlesType.select(ArticlesType.q.id == a.get("type")).getOne(default=None)
            article = Articles.select(Articles.q.id == a.get("id")).getOne(default=None)
            if article is None:
                Articles(   id = a.get('id'), 
                            prefix = a.get('prefix'),
                            type = articlestype.id,
                            title = a.get('title'),
                            header = u"ヘッダータイトル [" + a.get('title') + "]",
                            lead = u"リード リード リード リード リード リード リード リード リード リード リード リード リード リード リード",
                            template_set = a.get('template_set'),
                            template_system_use = a.get('template_system_use'),
                            default_template = a.get('default_template'),
                            password = a.get('password'),
                )
                article = Articles.select(Articles.q.id == a.get("id")).getOne(default=None)
            else:
                article.prefix = a.get('prefix')
                article.title = a.get('title')
                article.type = articlestype.id
                article.template_set = a.get('template_set')
                article.template_system_use = a.get('template_system_use')
                article.default_template = a.get('default_template')
                article.password = a.get('password')

        #ARTICLE TEMPALTE COPY
        tempdir = os.path.join( PANEO_ROOT, './paneo_page_templates/' + article.template_set + '/').replace('\\','/')
        ptmps = glob.glob( tempdir + '*.html')
        artdir = PANEO_SITE_DATA_DIR+'/__art__'+article.prefix + '__'
        for f in ptmps:
            fname = os.path.split(f)[1]
            if not os.path.exists(artdir+fname):
                shutil.copyfile(f,artdir+fname)

        return render.login()


    def POST( self ):

        web.ctx.session.loggedin = False 

        i = web.input()
        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        
        if dic.get("admin_password") == i.password :
            web.ctx.session.loggedin = True
            web.ctx.session.admin = True
        if dic.get("user_password") == i.password :
            web.ctx.session.loggedin = True
            web.ctx.session.admin = False 

        dic.close()

        return web.seeother('http://' + web.ctx.host + '/paneo/')



class Logout:
    def GET( self ):
        web.ctx.session.kill() 
        return web.seeother('http://' + web.ctx.host + '/paneo/login/')



## DUMMY POST
def testdummypost():
    #Posts.select( Posts.q.articles == article ).limit(10) 
    #DUMMY POST
    file = codecs.open(PANEO_SITE_DATA_DIR+'index.html',"r","utf8")
    html_file=file.read()
    file.close()
    #Articles._connection.debug = True
    for a in ARTICLES:
        article = Articles.select(Articles.q.prefix == a.get("prefix")).getOne(default=None)
        group = Groups.select(AND(Groups.q.articlestype == article.type , Groups.q.code == '0000')).getOne(default=None)
        category = Categories.select(AND(Categories.q.articlestype == article.type , Categories.q.code == '0000')).getOne(default=None)
        if len(article.posts) == 0:
            for i in range(1,500):
                posts = Posts(  
                    article = article, 
                    slug = ("post_%s_%s" % (article.prefix,i)),
                    key = "",
                    title = u"%sのダミー記事 %s" % ( article.title , i ), 
                    group = group,
                    password = "",
                    template = 'skelton',
                    #date = DateTimeCol(notNone=1,default=DateTimeCol.now)
                    #rawtext = UnicodeCol()
                    #label1 = UnicodeCol()
                    #label2 = UnicodeCol()
                    #label3 = UnicodeCol()
                    #viewed = BoolCol(notNone=1, default=True)
                    #created = DateTimeCol(notNone=1,default=DateTimeCol.now)
                )
                posts.addCategories(category)

#TEST DATA
#sqlhub.doInTransaction(testdummypost)
